package com.atguigu.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.servicebase.exception.GuliException;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.ExcelSubjectData;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author JY
 * @create 2021-01-18 23:26
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    //由于SubjectExcelListener需要自己new,不能交给Spring管理，所以注入不了其他对象，也就实现不了数据库操作
    //我们需要创建一个属性，在它new的时候赋值，相当于注入进来
    public EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectExcelListener() {
    }

    //一行一行读取时做的操作
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if(excelSubjectData==null){
            throw  new GuliException(20001,"文件为空！");
        }

        //一行一行读取，每次两个值：一级分类和二级分类
        EduSubject oneSubject = existOneSubject(subjectService, excelSubjectData.getOneSubjectName());
        if (oneSubject == null) {//没有相同的一级分类，可以添加
            oneSubject = new EduSubject();
            oneSubject.setTitle(excelSubjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            subjectService.save(oneSubject);
        }

        EduSubject twoSubject = existTwoSubject(subjectService, excelSubjectData.getTwoSubjectName(),
                oneSubject.getId());
        if (twoSubject == null) {//没有相同的二级分类，可以添加
            twoSubject = new EduSubject();
            twoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            twoSubject.setParentId(oneSubject.getId());
            subjectService.save(twoSubject);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String oneName){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        wrapper.eq("title",oneName);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String twoName,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",pid);
        wrapper.eq("title",twoName);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    //读取完毕做的操作
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
